//
//  ZLLearnSelectionViewController.m
//  ZLExamination
//
//  Created by Lei_Zhong_Xun on 2017/8/22.
//  Copyright © 2017年 Zheng. All rights reserved.
//

#import "ZLLearnSelectionViewController.h"
#import "ZLLearnSelectionBottomButtonView.h"
#import "ZLCourseLerningDetailModel.h"
#import "ZLExamBeginExitPromptView.h"
#import "ZLExciseBeginViewController.h"
#import "ZLBaseNavigationController.h"
#import "ZLLearnSelectionCell.h"

@interface ZLLearnSelectionViewController ()

/** 按钮背景view*/
@property (nonatomic,strong) ZLLearnSelectionBottomButtonView* buttonView;
@property (nonatomic, strong) ZLCourseLerningDetailListModel *detailModel;
@property (nonatomic, strong) ZLExamBeginExitPromptView *promptView; //退出提示

@property (nonatomic) BOOL isRecord; //是否记录学习时间
@property (nonatomic) NSInteger startTime;

@end

@implementation ZLLearnSelectionViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _startTime = [[NSDate date] timeIntervalSince1970];
    
    self.myTableView.rowHeight = UITableViewAutomaticDimension;
    self.myTableView.estimatedRowHeight = kSCREENH_HEIGHT;
    [self.myTableView registerClass:[ZLLearnSelectionCell class] forCellReuseIdentifier:@"kZLLearnSelectionCell_ID"];
    self.myTableView.backgroundColor = [UIColor whiteColor];
    [self.myTableView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(self.view);
        make.bottom.equalTo(self.view).offset(-40);
    }];
    
    self.navigationItem.title = _model.title;
    self.view.backgroundColor = [UIColor whiteColor];

    
    //添加完这个按钮view 不显示3个button
    [self.view addSubview:self.buttonView];
    [[UIApplication sharedApplication].keyWindow addSubview:self.promptView];
    [self loadData];

    
    __weak typeof(self) weakSelf = self;
    //提交学习记录
    [_promptView setEnterCallBack:^{
        
        NSInteger minute = [weakSelf getLearnTimeMinute];
        if (minute == 0) {
            weakSelf.isRecord = YES;
            ZLExciseBeginViewController *exciseVC = [[ZLExciseBeginViewController alloc] init];
            exciseVC.model = weakSelf.model;
            ZLBaseNavigationController *nav = [[ZLBaseNavigationController alloc] initWithRootViewController:exciseVC];
            [weakSelf presentViewController:nav animated:YES completion:nil];
        } else {
            NSString *curriculum_id = weakSelf.model.curriculum_id;
            NSDictionary *param = @{@"curriculum_id":curriculum_id,
                                    @"the_read_time" : @(minute)};
            
            if (!weakSelf.isRecord) {
                [[YCRequestDataService sharedManager] Post:@"curriculum/curriculum/stop_curriculum" parameters:param success:^(id response) {
                    if (response[@"error_code"]) {
                        NSLog(@"%@",response[@"error_msg"]);
                    } else {
                        weakSelf.isRecord = YES;
                    }
                } failure:^{
                    NSLog(@"网络或服务器出错");
                }];
            } else {
                ZLExciseBeginViewController *exciseVC = [[ZLExciseBeginViewController alloc] init];
                exciseVC.model = weakSelf.model;
                ZLBaseNavigationController *nav = [[ZLBaseNavigationController alloc] initWithRootViewController:exciseVC];
                [weakSelf presentViewController:nav animated:YES completion:nil];
            }
        }
    }];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(popToCourseLearningDetail) name:@"kExerciseResultDismissNotification" object:nil];

}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"kExerciseResultDismissNotification" object:nil];
}

- (void)popToCourseLearningDetail {
#pragma mark 练习结果关闭跳转详情
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"kExerciseResultDismissNotification" object:nil];
    
    [self.navigationController popViewControllerAnimated:NO];
    
}


- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    if (!_isRecord) {
        NSInteger minute = [self getLearnTimeMinute];
        if (minute > 0) {
            NSDictionary *param = @{@"curriculum_id":_model.curriculum_id,
                                    @"the_read_time" : @(minute)};
            [[YCRequestDataService sharedManager] Post:@"curriculum/curriculum/stop_curriculum" parameters:param success:^(id response) {
                if (response[@"error_code"]) {
                    NSLog(@"%@",response[@"error_msg"]);
                } else {
                    _isRecord = YES;
                }
            } failure:^{
                NSLog(@"网络或服务器出错");
            }];
        }
    }
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ZLLearnSelectionCell *cell = [tableView dequeueReusableCellWithIdentifier:@"kZLLearnSelectionCell_ID" forIndexPath:indexPath];
    
    NSAttributedString *attrStr = [[NSAttributedString alloc] initWithData:[_detailModel.content dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType} documentAttributes:nil error:nil];
    
    cell.contentLbl.attributedText = attrStr;
    
    return cell;
}

#pragma mark - 加载数据
- (void)loadData {
    
    NSString *curriculum_id = _model.curriculum_id;
    NSString *chapter_id = _model.k_id;
    
    NSDictionary *param = @{@"curriculum_id":curriculum_id,
                            @"chapter_id" : chapter_id};
    
    [[YCRequestDataService sharedManager] Post:@"curriculum/curriculum/chapter_info" parameters:param success:^(id response) {
        if (response[@"error_code"]) {
            NSLog(@"%@",response[@"error_msg"]);
        } else {
            
            _startTime = [[NSDate date] timeIntervalSince1970];
            
            _detailModel = [[ZLCourseLerningDetailListModel alloc] initWithDataDic:response[@"response_data"][@"lists"]];
            
            [self.myTableView reloadData];
        }
    } failure:^{
        NSLog(@"网络或服务器出错");
    }];
    
}
#pragma mark - 按钮点击事件

//目录
- (void)catalogueButtonClick: (UIButton *)sender
{
    
    NSLog(@"开始练习");
    [_promptView showExitPromptView];
    
}


- (NSInteger)getLearnTimeMinute {
    NSInteger second = ([[NSDate date] timeIntervalSince1970] - _startTime);
    if (second < 60 && second >= 30) second = 1;
    NSInteger minute = second/60;
    return minute;
}


#pragma mark -  布局

- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];

    [_buttonView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(44);
        make.left.right.bottom.equalTo(self.view);

    }];
}



#pragma mark - lazy load
- (UIView *)buttonView
{
    if (!_buttonView) {
        _buttonView = [[ZLLearnSelectionBottomButtonView alloc] init];
        _buttonView.backgroundColor = [UIColor clearColor];
        [_buttonView.catalogueButton addTarget:self action:@selector(catalogueButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _buttonView;
}
- (ZLExamBeginExitPromptView *)promptView {
    if (!_promptView) {
        _promptView = [[ZLExamBeginExitPromptView alloc] initWithFrame:kSCREEN_BOUNDS];
        _promptView.titleLbl.text = @"是否进入练习";
        _promptView.contentLbl.text = @"进入练习后，将退出学习";
    }
    return _promptView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
